package de.projectgoodmorning.bluetooth;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import de.projectgoodmorning.util.ArgsValidator;

public class ServerThread extends Thread {

	private Processable mProcessable;
	private String uuid;
	
	public ServerThread( String uuid, Processable processable ) {
		ArgsValidator.isNotNullAndNotEmpty( uuid, "uuid" );
		ArgsValidator.isNotNull( processable, "processable" );
		
		mProcessable = processable;
		this.uuid = uuid;
	}

	public void run() {
		LocalDevice local = null;

		StreamConnectionNotifier notifier;
		StreamConnection connection = null;

		// setup the server to listen for connection
		try {
			local = LocalDevice.getLocalDevice();
			local.setDiscoverable( DiscoveryAgent.GIAC );

			System.out.println( uuid.toString() );

			String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
			notifier = ( StreamConnectionNotifier ) Connector.open( url );
		} catch( Exception e ) {
			// TODO: Use a Logger
			e.printStackTrace();
			return;
		}

		// waiting for connection
		while( true ) {
			try {
				System.out.println( "waiting for connection..." );

				connection = notifier.acceptAndOpen();

				Thread processThread = new ProcessThread( connection, mProcessable );
				processThread.start();

			} catch( Exception e ) {
				e.printStackTrace();
				return;
			}
		}
	}
}
